<template>
  <view class="banner-container">
    <swiper 
      class="banner" 
      :class="{ 'loaded': bannerLoaded }"
      :circular="shouldUseCircular"
      :autoplay="false"
      :interval="interval"
      :duration="duration"
      :indicator-dots="indicatorDots"
      :indicator-color="indicatorColor"
      :indicator-active-color="indicatorActiveColor"
      :current="currentIndex"
      :skip-hidden-item-layout="true"
      :disable-touch="false"
      v-if="banners.length > 0"
      @change="onBannerChange"
      @animationfinish="onAnimationFinish"
      @transition="onTransition"
    >
      <swiper-item v-for="(item, index) in banners" :key="item.bannerId || index" @click="onBannerClick(item)">
        <video
          v-if="item.bannerType == 2"
          :src="getFullUrl(item.imageUrl)"
          class="banner-img"
          :controls="false"
          :autoplay="false"
          :loop="true"
          :muted="true"
          object-fit="cover"
          :show-center-play-btn="false"
          :show-play-btn="false"
          :enable-progress-gesture="false"
          :show-fullscreen-btn="false"
          :enable-play-gesture="false"
          :auto-pause-if-navigate="true"
          :auto-pause-if-open-native="true"
          @error="onImageError"
          @load="onVideoLoad"
        ></video>
        <view v-else-if="item.bannerType == 3" class="banner-vr-wrapper">
          <image 
            :src="getFullUrl(item.imageUrl)" 
            class="banner-img" 
            mode="aspectFill"
            @error="onImageError"
            @load="onImageLoad"
          ></image>
          <view class="vr-icon">
            <image src="/static/assets/public/vr-icon.png" />
          </view>
        </view>
        <image 
          v-else
          :src="getFullUrl(item.imageUrl)" 
          class="banner-img" 
          mode="aspectFill"
          @error="onImageError"
          @load="onImageLoad"
        ></image>
      </swiper-item>
    </swiper>
  </view>
</template>

<script>
import { getFullUrl } from '@/utils/url-helper.js';
import { handleVideoError } from '@/utils/video-helper.js';

export default {
  name: 'BannerSwiper',
  props: {
    banners: {
      type: Array,
      default: () => []
    },
    interval: {
      type: Number,
      default: 4000
    },
    duration: {
      type: Number,
      default: 500
    },
    indicatorDots: {
      type: Boolean,
      default: true
    },
    indicatorColor: {
      type: String,
      default: '#ffffff'
    },
    indicatorActiveColor: {
      type: String,
      default: '#ff0000'
    },
    autoplay: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      bannerLoaded: false,
      imageLoadCount: 0,
      totalImages: 0,
      currentIndex: 0,
      isAnimating: false, // 防止动画过程中的闪烁
      autoplayTimer: null, // 自动播放定时器
      isTransitioning: false, // 是否正在过渡
      transitionTimer: null // 过渡定时器
    }
  },
  computed: {
    // 小程序中，当banner数量小于等于2时，禁用循环滚动避免闪烁
    shouldUseCircular() {
      return this.banners.length > 2;
    }
  },
  watch: {
    banners: {
      handler(newBanners) {
        if (newBanners && newBanners.length > 0) {
          this.totalImages = newBanners.length;
          this.imageLoadCount = 0;
          this.bannerLoaded = false;
          // 重置当前索引
          this.currentIndex = 0;
          this.isAnimating = false;
          this.isTransitioning = false;
        }
      },
      immediate: true
    },
    
    // 监听autoplay变化，手动控制自动播放
    autoplay: {
      handler(newVal) {
        if (newVal) {
          this.startAutoplay();
        } else {
          this.stopAutoplay();
        }
      },
      immediate: true
    }
  },
  methods: {
    getFullUrl,
    
    onBannerChange(e) {
      const newIndex = e.detail.current;
      // 防止索引越界
      if (newIndex >= 0 && newIndex < this.banners.length) {
        this.currentIndex = newIndex;
      }
      this.$emit('change', e.detail);
    },
    
    // 动画完成事件，用于防止闪烁
    onAnimationFinish(e) {
      this.isAnimating = false;
      this.isTransitioning = false;
      const newIndex = e.detail.current;
      if (newIndex >= 0 && newIndex < this.banners.length) {
        this.currentIndex = newIndex;
      }
    },
    
    // 过渡事件，用于处理循环滚动时的闪烁
    onTransition(e) {
      this.isTransitioning = true;
      // 清除之前的定时器
      if (this.transitionTimer) {
        clearTimeout(this.transitionTimer);
      }
      // 设置过渡完成定时器
      this.transitionTimer = setTimeout(() => {
        this.isTransitioning = false;
      }, this.duration + 100);
    },
    
    onBannerClick(banner) {
      // 检查是否有链接配置
      if (!banner.linkUrl) {
        return;
      }
      
      try {
        if (banner.linkType === 1) {
          // 跳转到web页面
          // #ifdef H5
          window.open(banner.linkUrl, '_blank');
          // #endif
          // #ifdef MP-WEIXIN
          uni.navigateTo({
            url: `/pages/webview/webview?url=${encodeURIComponent(banner.linkUrl)}`
          });
          // #endif
          // #ifdef APP-PLUS
          plus.runtime.openURL(banner.linkUrl);
          // #endif
        } else if (banner.linkType === 2) {
          // 跳转到路由页面
          if (banner.linkUrl.startsWith('/')) {
            // 绝对路径
            uni.navigateTo({
              url: banner.linkUrl
            });
          } else {
            // 相对路径，添加前缀
            uni.navigateTo({
              url: `/${banner.linkUrl}`
            });
          }
        }
      } catch (error) {
        console.error('Banner跳转失败:', error);
        uni.showToast({
          title: '跳转失败',
          icon: 'none'
        });
      }
    },
    
    onImageLoad() {
      this.imageLoadCount++;
      this.checkBannerLoaded();
    },
    
    onVideoLoad(e) {
      this.imageLoadCount++;
      this.checkBannerLoaded();
    },
    
    checkBannerLoaded() {
      if (this.imageLoadCount >= this.totalImages && !this.bannerLoaded) {
        this.bannerLoaded = true;
        this.$emit('loaded');
      }
    },
    
    onImageError(e) {
      const currentBanner = this.banners[this.currentIndex];
      if (currentBanner && currentBanner.bannerType === 2) {
        const errorResult = handleVideoError(e, currentBanner);
        this.$emit('error', {
          type: 'video',
          error: e,
          banner: currentBanner,
          result: errorResult
        });
      } else {
        this.$emit('error', {
          type: 'image',
          error: e,
          banner: currentBanner
        });
      }
    },
    
    setLoaded() {
      this.bannerLoaded = true;
    },
    
    // 手动控制自动播放，避免小程序原生autoplay的闪烁问题
    startAutoplay() {
      this.stopAutoplay(); // 先清除之前的定时器
      if (this.banners.length > 1) {
        this.autoplayTimer = setInterval(() => {
          if (!this.isAnimating && !this.isTransitioning) {
            this.next();
          }
        }, this.interval);
      }
    },
    
    stopAutoplay() {
      if (this.autoplayTimer) {
        clearInterval(this.autoplayTimer);
        this.autoplayTimer = null;
      }
      if (this.transitionTimer) {
        clearTimeout(this.transitionTimer);
        this.transitionTimer = null;
      }
    },
    
    toggleAutoplay() {
      if (this.autoplay) {
        this.stopAutoplay();
        this.autoplay = false;
      } else {
        this.autoplay = true;
        this.startAutoplay();
      }
    },
    
    // 手动切换到指定索引
    goToIndex(index) {
      if (index >= 0 && index < this.banners.length && !this.isAnimating && !this.isTransitioning) {
        this.isAnimating = true;
        this.currentIndex = index;
      }
    },
    
    // 切换到下一个
    next() {
      if (this.isAnimating || this.isTransitioning) return;
      
      this.isAnimating = true;
      if (this.shouldUseCircular) {
        // 循环模式下，可以无限循环
        const nextIndex = (this.currentIndex + 1) % this.banners.length;
        this.currentIndex = nextIndex;
      } else {
        // 非循环模式下，到达最后一个时停止
        if (this.currentIndex < this.banners.length - 1) {
          this.currentIndex = this.currentIndex + 1;
        } else {
          this.isAnimating = false;
        }
      }
    },
    
    // 切换到上一个
    prev() {
      if (this.isAnimating || this.isTransitioning) return;
      
      this.isAnimating = true;
      if (this.shouldUseCircular) {
        // 循环模式下，可以无限循环
        const prevIndex = this.currentIndex === 0 ? this.banners.length - 1 : this.currentIndex - 1;
        this.currentIndex = prevIndex;
      } else {
        // 非循环模式下，到达第一个时停止
        if (this.currentIndex > 0) {
          this.currentIndex = this.currentIndex - 1;
        } else {
          this.isAnimating = false;
        }
      }
    },
    
    reset() {
      this.bannerLoaded = false;
      this.imageLoadCount = 0;
      this.currentIndex = 0;
      this.isAnimating = false;
      this.isTransitioning = false;
      this.stopAutoplay();
    }
  },
  
  beforeDestroy() {
    this.stopAutoplay();
  }
}
</script>

<style lang="less" scoped>
.banner-container {
  width: 100%;
  margin-bottom: 16rpx;
}

.banner {
  margin: 10rpx 20rpx;
  width: auto;
  height: 330rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.1);
  position: relative;
  border-radius: 24rpx; // 添加圆角
  // cursor: pointer; // 添加手型光标
  
  // 去除swiper的遮罩层
  &::after {
    display: none !important;
  }
  
  // 设置swiper-item的遮罩为透明
  /deep/ .swiper-item {
    &::after {
      background: transparent !important;
      opacity: 0 !important;
      display: none !important;
    }
    
    // 针对安卓的额外处理
    &::before {
      background: transparent !important;
      opacity: 0 !important;
      display: none !important;
    }
  }
  
  // 针对小程序swiper的遮罩处理
  /deep/ .uni-swiper-wrapper {
    &::after {
      background: transparent !important;
      opacity: 0 !important;
      display: none !important;
    }
    
    &::before {
      background: transparent !important;
      opacity: 0 !important;
      display: none !important;
    }
  }
  
  // 去除点击时的遮罩效果
  /deep/ .uni-swiper-item {
    &::after {
      background: transparent !important;
      opacity: 0 !important;
      display: none !important;
    }
    
    &::before {
      background: transparent !important;
      opacity: 0 !important;
      display: none !important;
    }
  }
  
  // 针对安卓系统的特殊处理
  /deep/ .swiper-wrapper {
    transform-style: preserve-3d;
    backface-visibility: hidden;
    
    &::after {
      background: transparent !important;
      opacity: 0 !important;
      display: none !important;
    }
    
    &::before {
      background: transparent !important;
      opacity: 0 !important;
      display: none !important;
    }
  }
  
  // 优化过渡效果
  /deep/ .swiper-item {
    transform-style: preserve-3d;
    backface-visibility: hidden;
    will-change: transform;
    
    // 安卓系统遮罩处理
    &::after {
      background: transparent !important;
      opacity: 0 !important;
      display: none !important;
    }
    
    &::before {
      background: transparent !important;
      opacity: 0 !important;
      display: none !important;
    }
  }

  .banner-img {
    width: auto;
    height: 100%;
    display: block;
    object-fit: cover;
    // transition: transform 0.3s ease;
    border-radius: 24rpx; // 图片也加圆角，防止溢出
    // 防止图片闪烁
    transform: translateZ(0);
    backface-visibility: hidden;
  }
  
  // 添加点击效果
  swiper-item {
    // cursor: pointer;
    // transition: transform 0.2s ease;
    
    // &:active {
    //   transform: scale(0.98);
    // }
  }
  
  // &::before {
  //   content: '';
  //   position: absolute;
  //   top: 50%;
  //   left: 50%;
  //   width: 40rpx;
  //   height: 40rpx;
  //   margin: -20rpx 0 0 -20rpx;
  //   border: 4rpx solid #f3f3f3;
  //   border-top: 4rpx solid var(--primary-color);
  //   border-radius: 50%;
  //   animation: spin 1s linear infinite;
  //   z-index: 1;
  // }
  
  // &.loaded::before {
  //   display: none;
  // }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.banner-vr-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 24rpx; // VR包裹也加圆角

  .vr-icon {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    z-index: 2;
    
    image {
      width: 60rpx;
      height: 60rpx;
    }
  }
}

// 针对安卓系统的全局样式覆盖
// #ifdef MP-WEIXIN
.banner {
  /deep/ .swiper-item {
    -webkit-tap-highlight-color: transparent !important;
    -webkit-touch-callout: none !important;
    -webkit-user-select: none !important;
    user-select: none !important;
    
    &::after {
      background: transparent !important;
      opacity: 0 !important;
      display: none !important;
      visibility: hidden !important;
    }
    
    &::before {
      background: transparent !important;
      opacity: 0 !important;
      display: none !important;
      visibility: hidden !important;
    }
  }
  
  /deep/ .uni-swiper-item {
    -webkit-tap-highlight-color: transparent !important;
    -webkit-touch-callout: none !important;
    -webkit-user-select: none !important;
    user-select: none !important;
    
    &::after {
      background: transparent !important;
      opacity: 0 !important;
      display: none !important;
      visibility: hidden !important;
    }
    
    &::before {
      background: transparent !important;
      opacity: 0 !important;
      display: none !important;
      visibility: hidden !important;
    }
  }
}
// #endif
</style>
